var Inbox = function () {

    var content = $('.inbox-content');
    var loading = $('.inbox-loading');
    var listListing = '';
    var user;

    var getInboxHtml = function (src, title, category, pageMap) {

        var funLoadName = '收信箱' == title ? 'loadInbox' : '发信箱' == title ? 'loadSent' : '草案箱' == title ? 'loadDraft' : '垃圾箱' == title ? 'loadTrash' : '';
        var name = '收信箱' == title ? 'inbox' : '发信箱' == title ? 'sent' : '草案箱' == title ? 'draft' : '垃圾箱' == title ? 'trash' : '';

        var lastPage = pageMap.page - 1;
        var nextPage = pageMap.page + 1;

        var leftFun = pageMap.page > 1 ? 'onclick="Inbox.' + funLoadName + '(' + '$(this),' + '\'' + name + '\',' + '\'' + title + '\',' + lastPage + ')"' : '';
        var RightFun = pageMap.page < pageMap.sumPage ? 'onclick="Inbox.' + funLoadName + '(' + '$(this),' + '\'' + name + '\',' + '\'' + title + '\',' + nextPage + ')"' : '';

        var hasInboxHtml = category == 1 ? '<li>'
            + '                                 <a href="javascript:" onclick="markRead()">'
            + '                                     <i class="fa fa-pencil"></i> 标志为已读'
            + '                                 </a>'
            + '                             </li>' : '';
        var html = '<table class="table table-striped table-advance table-hover">'
            + '      <thead>'
            + '          <tr>'
            + '              <th colspan="3">'
            + '                  <input type="checkbox" class="mail-checkbox mail-group-checkbox">'
            + '                  <div class="btn-group">'
            + '                      <a class="btn btn-sm blue" href="#" data-toggle="dropdown">'
            + '                          操作 <i class="fa fa-angle-down"></i>'
            + '                      </a>'
            + '                      <ul class="dropdown-menu">'
//          当时收件箱的时候才有操作接口
            + hasInboxHtml
            + '                          <li>'
            + '                              <a href="javascript:" onclick="markTrash()">'
            + '                                  <i class="fa fa-trash-o"></i> 垃圾邮件'
            + '                              </a>'
            + '                          </li>'
            + '                          <li class="divider">'
            + '                          </li>'
            + '                          <li>'
            + '                              <a href="javascript:" onclick="del()">'
            + '                                  <i class="fa fa-ban"></i> 删除'
            + '                              </a>'
            + '                          </li>'
            + '                      </ul>'
            + '                  </div>'
            + '              </th>'
            + '              <th class="pagination-control" colspan="3">'
            + '                  <span class="pagination-info">'
            + '                      ' + (pageMap.beginCount + 1) + '-' + pageMap.endCount + '共' + pageMap.sumPage + '页'
            + '                  </span>'
            + '                  <a class="btn btn-sm blue" ' + leftFun + '>'
            + '                      <i class="fa fa-angle-left"></i>'
            + '                  </a>'
            + '                  <a class="btn btn-sm blue" ' + RightFun + '>'
            + '                      <i class="fa fa-angle-right"></i>'
            + '                  </a>'
            + '              </th>'
            + '          </tr>'
            + '      </thead>'
            + '      <tbody>';
        for (var i = pageMap.beginCount; i < pageMap.endCount; i++) {
            html += getTdHtml(src[i], title);
        }
        html += '     </tbody>'
            + '  </table>';
        return html;
    };

    function getTdHtml(data, title) {
        var started = data.state != 1 ? 'inbox-started' : '';
        return '<tr class="unread" data-messageid="' + data.id + '">'
            + '          <td class="inbox-small-cells">'
            + '              <input type="checkbox" class="mail-checkbox" name="mail-checkbox" value="' + data.id + '">'
            + '          </td>'
            + '          <td class="inbox-small-cells">'
            + '              <i class="fa fa-star ' + started + '"></i>'
            + '          </td>'
            + '          <td class="view-message hidden-xs">'
            + '              ' + data.user.userName
            + '          </td>'
            + '          <td class="view-message ">'
            + '              ' + data.content.substring(0, 40) + '....'
            + '          </td>'
            + '          <td class="view-message text-right" colspan="3">'
            + '              ' + data.sendDate.substring(0, 19)
            + '          </td>'
            + '      </tr>';
    }

    var getComposeHtml = function () {
        return '   <form class="inbox-compose form-horizontal">' +
            '          <div class="inbox-compose-btn">' +
            '              <a class="btn blue" style="height:25px; padding-top: 2px !important;" onclick="Inbox.sentInbox()">发送</a>' +
            '              <a class="btn blue" style="height:25px; padding-top: 2px !important;" onclick="Inbox.draftInbox()">草案</a>' +
            '          </div>' +
            '          <div class="inbox-form-group mail-to">' +
            '              <label class="control-label"><a style="color: red">发送给:</a></label>' +
            '              <div class="controls controls-to">' +
            '                  <input type="text" id="addresseeName" placeholder="请输入或在尾端选择好友" class="form-control" name="to">' +
            '                  <input type="hidden" id="addresseeId" class="form-control" name="to">' +
            '                  <span class="inbox-cc-bcc">' +
            '                  </span>' +
            '              </div>' +
            '          </div>' +
            '          <div class="inbox-form-group">' +
            '              <textarea class="inbox-editor inbox-wysihtml5 form-control" id="message" name="message" rows="12"></textarea>' +
            '          </div>' +
            '      </form>';
    };

    var getMessageHtml = function (src) {
        var title = "";
        switch (src.category) {
            case 1:
                title = '来自您的收件箱 <a href="javascript:" onclick="$(\'.inbox-nav > li.inbox > a\').click()">收件箱</a>';
                break;
            case 2:
                title = '来自您的发件箱 <a href="javascript:" onclick="$(\'.inbox-nav > li.sent > a\').click()">发件箱</a>';
                break;
            case 3:
                title = '来自您的草案箱 <a href="javascript:" onclick="$(\'.inbox-nav > li.draft > a\').click()">草案箱</a>';
                break;
            case 4:
                title = '来自您的垃圾箱 <a href="javascript:" onclick="$(\'.inbox-nav > li.trash > a\').click()">垃圾箱</a>';
                break;
        }

        var ifMe = src.category == 1;

        var from = ifMe ? src.user.userName : '我';

        var to = !ifMe ? src.category == 3 ? '' : src.user.userName : '我';

        var showOperate = src.user.id > 0 ? src.state == 2 && src.category == 1 ? '同意' : '回复' : '删除';

        var funOperate = src.user.id > 0 ? src.state == 2 && src.category == 1 ? 'top.dealFriendApply(' + src.id + ',' + src.userId + ',' + src.addresseeId + ',' + true + ')' : '$(\'.compose-btn a\').click()' : 'delInbox(' + src.id + ')';

        var operate = src.user.id > 0 ? (src.state == 2 && src.category == 1) ? (
            '                       <li>' +
                '                           <a href="javascript:" onclick="top.dealFriendApply(' + src.id + ',' + src.userId + ',' + src.addresseeId + ',' + true + ')">' +
                '                               <i class="fa fa-arrow-right reply-btn"></i> 同意加为好友' +
                '                           </a>' +
                '                       </li>' +
                '                       <li>' +
                '                           <a href="javascript:" onclick="top.dealFriendApply(' + src.id + ',' + src.userId + ',' + src.addresseeId + ',' + false + ')">' +
                '                               <i class="fa fa-arrow-left reply-btn"></i> 拒绝加为好友' +
                '                           </a>' +
                '                       </li>' +
                '                       <li class="divider"> </li>' +
                '                       <li>' +
                '                           <a href="javascript:" onclick="delInbox(' + src.id + ')">' +
                '                               <i class="fa fa-ban"></i> 删除' +
                '                           </a>' +
                '                       </li>') : (
            '                           <li>' +
                '                           <a href="javascript:" onclick="Inbox.loadCompose()">' +
                '                               <i class="fa fa-reply reply-btn"></i> 回复' +
                '                           </a>' +
                '                       </li>' +
                '                       <li class="divider"> </li>' +
                '                       <li>' +
                '                           <a href="javascript:" onclick="markTrashInbox(' + src.id + ')">' +
                '                               <i class="fa fa-trash-o"></i> 垃圾邮件' +
                '                           </a>' +
                '                       </li>' +
                '                       <li>' +
                '                           <a href="javascript:" onclick="delInbox(' + src.id + ')">' +
                '                               <i class="fa fa-ban"></i> 删除' +
                '                           </a>' +
                '                       </li>') : (
            '                       <li>' +
                '                           <a href="javascript:" onclick="markTrashInbox(' + src.id + ')">' +
                '                               <i class="fa fa-trash-o"></i> 垃圾邮件' +
                '                           </a>' +
                '                       </li>' +
                '                       <li>' +
                '                           <a href="javascript:" onclick="delInbox(' + src.id + ')">' +
                '                               <i class="fa fa-ban"></i> 删除' +
                '                           </a>' +
                '                       </li>' );

        return '<div class="inbox-header inbox-view-header">' +
            '       <h1 class="pull-left">' +
            '       ' + title +
            '       </h1>' +
            '   </div>' +
            '   <div class="inbox-view-info">' +
            '       <div class="row">' +
            '           <div class="col-md-7">' +
            '               <img style="width: 25px;height: 25px" src="' + src.user.userBaseInfo.photoUrl + '">' +
            '               <span class="bold"> ' + from + ' </span>' +
            '               <span> &#60;' + src.user.userBaseInfo.email + '&#62; </span> 发给' +
            '               <span class="bold"> ' + to + ' </span> 在 ' + src.sendDate.substr(0, 19) +
            '           </div>' +
            '           <div class="col-md-5 inbox-info-btn">' +
            '               <div class="btn-group">' +
            '                   <a class="btn blue reply-btn" style="padding-top: 2px;padding-bottom: 3px;margin-top: 2px" onclick="' + funOperate + '">' +
            '                       <i class="fa fa-reply"></i> ' + showOperate +
            '                   </a>' +
            '                   <button class="btn blue dropdown-toggle" data-toggle="dropdown">' +
            '                       <i class="fa fa-angle-down"></i>' +
            '                   </button>' +
            '                   <ul class="dropdown-menu pull-right">' +
            '                       ' + operate +
            '                   </ul>' +
            '               </div>' +
            '           </div>' +
            '       </div>' +
            '       <div class="inbox-view">' +
            '           <p>' +
            '           ' + src.content +
            '           </p>' +
            '       </div>' +
            '   </div>';
    };

    var loadInbox = function (el, name, title, page) {
        var url = 'inbox/listAllInbox';
//        var title = $('.inbox-nav > li.' + name + ' a').attr('data-title');
        listListing = name;

        loading.show();
        content.html('');
        toggleButton(el);

        $.ajax({
            type: "POST",
            url: url,
            data: {
                state: -1,
                category: 1,
                page: page
            },
            dataType: "json",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-nav > li.' + name).addClass('active');
                $('.inbox-header > h1').text(title);

                loading.hide();
                $.ajax({
                    url: 'inbox/getPageMap',
                    type: "POST",
                    data: {
                        state: -1,
                        category: 1,
                        page: page
                    },
                    dataType: "json",
                    success: function (pageMap) {
                        content.html(getInboxHtml(res, "收信箱", 1, pageMap));
                    }
                });
                $("#countInbox").val(res.length);
                $("#countInboxBox").html("收信箱(" + res.length + ")");
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });

        // handle group checkbox:
        jQuery('body').on('change', '.mail-group-checkbox', function () {
            var set = jQuery('.mail-checkbox');
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                $(this).attr("checked", checked);
            });
            jQuery.uniform.update(set);
        });

        // handle group checkbox:
        jQuery('body').on('change', '.mail-checkbox', function () {
            var set = jQuery('.mail-checkbox');
            var checked = jQuery(this).is(":checked");
            $(this).attr("checked", checked);
            jQuery.uniform.update(set);
        });
    };

    var loadSent = function (el, name, title, page) {
        var url = 'inbox/listAllInbox';
//        var title = $('.inbox-nav > li.' + name + ' a').attr('data-title');
        listListing = name;

        loading.show();
        content.html('');
        toggleButton(el);

        $.ajax({
            type: "POST",
            url: url,
            data: {
                state: -1,
                category: 2
            },
            dataType: "json",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-nav > li.' + name).addClass('active');
                $('.inbox-header > h1').text(title);

                loading.hide();

                $.ajax({
                    url: 'inbox/getPageMap',
                    type: "POST",
                    data: {
                        state: -1,
                        category: 2,
                        page: page
                    },
                    dataType: "json",
                    success: function (pageMap) {
                        content.html(getInboxHtml(res, "发信箱", 0, pageMap));
                    }
                });

                $("#countSent").val(res.length);
                $("#countSentBox").html("发信箱(" + res.length + ")");
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });

        // handle group checkbox:
        jQuery('body').on('change', '.mail-group-checkbox', function () {
            var set = jQuery('.mail-checkbox');
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                $(this).attr("checked", checked);
            });
            jQuery.uniform.update(set);
        });
    };

    var loadDraft = function (el, name, title, page) {
        var url = 'inbox/listAllInbox';
//        var title = $('.inbox-nav > li.' + name + ' a').attr('data-title');
        listListing = name;

        loading.show();
        content.html('');
        toggleButton(el);

        $.ajax({
            type: "POST",
            url: url,
            data: {
                state: -1,
                category: 3,
                page: page
            },
            dataType: "json",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-nav > li.' + name).addClass('active');
                $('.inbox-header > h1').text(title);

                loading.hide();

                $.ajax({
                    url: 'inbox/getPageMap',
                    type: "POST",
                    data: {
                        state: -1,
                        category: 3
                    },
                    dataType: "json",
                    success: function (pageMap) {
                        content.html(getInboxHtml(res, "草案箱", 0, pageMap));
                    }
                });

                $("#countDraft").val(res.length);
                $("#countDraftBox").html("草案箱(" + res.length + ")");
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });

        // handle group checkbox:
        jQuery('body').on('change', '.mail-group-checkbox', function () {
            var set = jQuery('.mail-checkbox');
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                $(this).attr("checked", checked);
            });
            jQuery.uniform.update(set);
        });
    };

    var loadTrash = function (el, name, title, page) {
        var url = 'inbox/listAllInbox';
//        var title = $('.inbox-nav > li.' + name + ' a').attr('data-title');
        listListing = name;

        loading.show();
        content.html('');
        toggleButton(el);

        $.ajax({
            type: "POST",
            url: url,
            data: {
                state: 4,
                category: 0,
                page: page
            },
            dataType: "json",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-nav > li.' + name).addClass('active');
                $('.inbox-header > h1').text(title);

                loading.hide();
                $.ajax({
                    url: 'inbox/getPageMap',
                    type: "POST",
                    data: {
                        state: 4,
                        category: 0
                    },
                    dataType: "json",
                    success: function (pageMap) {
                        content.html(getInboxHtml(res, "垃圾箱", 0, pageMap));
                    }
                });

                $("#countTrash").val(res.length);
                $("#countTrashBox").html("垃圾箱(" + res.length + ")");
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });

        // handle group checkbox:
        jQuery('body').on('change', '.mail-group-checkbox', function () {
            var set = jQuery('.mail-checkbox');
            var checked = jQuery(this).is(":checked");
            jQuery(set).each(function () {
                $(this).attr("checked", checked);
            });
            jQuery.uniform.update(set);
        });
    };

    var loadCompose = function (el) {
        content.html('');

        $('.inbox-nav > li.active').removeClass('active');
        $('.inbox-header > h1').text('写邮件');

        loading.hide();

        content.html(getComposeHtml());
        $('#addresseeName').keyup(function (e) {
            Inbox.initSelectFriends($('#addresseeName').val().trim());
        }).keyup();

        initWysihtml5();
        $('.inbox-wysihtml5').focus();
        App.fixContentHeight();
        App.initUniform();
    };

    var loadMessage = function (el, name, resetMenu) {
        var url = 'inbox/checkMail';

        loading.show();
        content.html('');
        toggleButton(el);

        var message_id = el.parent('tr').attr("data-messageid");

        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: {
                id: message_id
            },
            success: function (res) {
                toggleButton(el);

                if (resetMenu) {
                    $('.inbox-nav > li.active').removeClass('active');
                }
                $('.inbox-header > h1').text('邮件信息');

                loading.hide();
                content.html(getMessageHtml(res));
                top.changeMailState(res.id);
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });
    };

    var initWysihtml5 = function () {
        $('.inbox-wysihtml5').wysihtml5({
            "stylesheets": ["assets/plugins/bootstrap-wysihtml5/wysiwyg-color.css"]
        });
    };

    var initFileupload = function () {

        $('#fileupload').fileupload({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: 'assets/plugins/jquery-file-upload/server/php/',
            autoUpload: true
        });

        // Upload server status check for browsers with CORS support:
        if ($.support.cors) {
            $.ajax({
                url: 'assets/plugins/jquery-file-upload/server/php/',
                type: 'HEAD'
            }).fail(function () {
                    $('<span class="alert alert-error"/>')
                        .text('Upload server currently unavailable - ' +
                            new Date())
                        .appendTo('#fileupload');
                });
        }
    };

    var loadReply = function (el) {
        var url = 'inbox_reply.html';

        loading.show();
        content.html('');
        toggleButton(el);

        // load the form via ajax
        $.ajax({
            type: "GET",
            cache: false,
            url: url,
            dataType: "html",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-header > h1').text('Reply');

                loading.hide();
                content.html(res);
                $('[name="message"]').val($('#reply_email_content_body').html());

                handleCCInput(); // init "CC" input field

                initFileupload();
                initWysihtml5();
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });
    };

    var loadSearchResults = function (el) {
        var url = 'inbox_search_result.html';

        loading.show();
        content.html('');
        toggleButton(el);

        $.ajax({
            type: "GET",
            cache: false,
            url: url,
            dataType: "html",
            success: function (res) {
                toggleButton(el);

                $('.inbox-nav > li.active').removeClass('active');
                $('.inbox-header > h1').text('Search');

                loading.hide();
                content.html(res);
                App.fixContentHeight();
                App.initUniform();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                toggleButton(el);
            },
            async: false
        });
    };

    var handleCCInput = function () {
        var the = $('.inbox-compose .mail-to .inbox-cc');
        var input = $('.inbox-compose .input-cc');
        the.hide();
        input.show();
        $('.close', input).click(function () {
            input.hide();
            the.show();
        });
    };

    var toggleButton = function (el) {
        if (typeof el == 'undefined') {
            return;
        }
        if (el.attr("disabled")) {
            el.attr("disabled", false);
        } else {
            el.attr("disabled", true);
        }
    };

    return {
        loadInbox: function (el, name, title, page) {
            loadInbox(el, name, title, page);
        },
        loadSent: function (el, name, title, page) {
            loadSent(el, name, title, page);
        },
        loadDraft: function (el, name, title, page) {
            loadDraft(el, name, title, page);
        },
        loadTrash: function (el, name, title, page) {
            loadTrash(el, name, title, page);
        },

        selectFriend: function (friendName, id) {
            $("#addresseeName").val(friendName);
            $("#addresseeId").val(id);
        },

        sentInbox: function () {
            $.ajax({
                url: "inbox/addInbox",
                data: {
                    content: $("#message").val(),
                    addresseeId: $("#addresseeId").val(),
                    state: 0,
                    category: 2
                },
                type: "POST",
                dataType: "json",
                success: function () {
                    top.bootbox.alert("发送成功！");
                    var $countSent = $("#countSent");
                    var countSent = $countSent.val() - -1;
                    $countSent.val(countSent);
                    $("#countSentBox").html("发信箱(" + countSent + ")");
                    loadCompose("");
                },
                error: function () {

                }
            })
        },

        draftInbox: function () {
            $.ajax({
                url: "inbox/addInbox",
                data: {
                    content: $("#message").val(),
                    addresseeId: $("#addresseeId").val(),
                    state: 0,
                    category: 3
                },
                type: "POST",
                dataType: "json",
                success: function () {
                    top.bootbox.alert("保存成功！");
                    var $countDraft = $("#countDraft");
                    var countDraft = $countDraft.val() - -1;
                    $countDraft.val(countDraft);
                    $("#countDraftBox").html("草案箱(" + countDraft + ")");
                    loadCompose("");
                },
                error: function () {

                }
            })
        },

        initSelectFriends: function (friendName) {
            $.ajax({
                url: "friend/listAllFriend",
                data: {
                    friendName: friendName
                },
                async: false,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    var innerHtml = "";
                    for (var i in data) {
                        if (i > 6) {
                            break;
                        }
                        innerHtml += '<span class="inbox-bcc" onclick="Inbox.selectFriend(\'' + data[i].friendName + '\',' + data[i].friendId + ')">' + data[i].friendName + '</span>';
                    }
                    $(".inbox-cc-bcc").html(innerHtml);
                },
                error: function () {
                }
            });
        },

        //main function to initiate the module
        init: function (_user) {
            user = _user;
            // handle compose btn click
            $('.inbox').on('click', '.compose-btn a', function () {
                loadCompose($(this));
            });

            // handle discard btn
            $('.inbox').on('click', '.inbox-discard-btn', function (e) {
                e.preventDefault();
                loadInbox($(this), listListing, "收信箱", 1);
            });

//            // handle reply and forward button click
//            $('.inbox').on('click', '.reply-btn', function () {
//                loadReply($(this));
//            });

            // handle view message
            $('.inbox-content').on('click', '.view-message', function () {
                loadMessage($(this));
            });

            // handle inbox listing
            $('.inbox-nav > li.inbox > a').click(function () {
                loadInbox($(this), 'inbox', '收信箱', 1);
            });

            // handle sent listing
            $('.inbox-nav > li.sent > a').click(function () {
                loadSent($(this), 'sent', '发信箱');
            });

            // handle  listing
            $('.inbox-nav > li.draft > a').click(function () {
                loadDraft($(this), 'draft', '草案箱');
            });

            // handle trash listing
            $('.inbox-nav > li.trash > a').click(function () {
                loadTrash($(this), 'trash', '垃圾箱');
            });

            //handle loading content based on URL parameter
            if (App.getURLParameter("a") === "view") {
                loadMessage();
            } else if (App.getURLParameter("a") === "compose") {
                loadCompose();
            } else {
                $('.inbox-nav > li.inbox > a').click();
            }
        }

    };

}();